﻿using IdentityModel.Client;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace MyHttpHelp
{
    /// <summary>
    /// 帮助类
    /// </summary>
    public class HttpHelp
    {
        /// <summary>
        /// 是否使用Token
        /// </summary>
        public bool IsUseToken {  get; set; }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="url"></param>
        public async void Get(string url)
        {
            var httpClient = HttpCreate();
            var response = await httpClient.GetAsync(url);
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"响应内容： {result}");
            }
            else
            {
                Console.WriteLine($"请求失败，状态码： {response.StatusCode}");
            }
        }

        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        public async void Post(string url, object data)
        {
            var value = System.Text.Json.JsonSerializer.Serialize(data);
            var httpClient = HttpCreate();
            var content = new StringContent(value, Encoding.UTF8, "application/json");
            var response = await httpClient.PostAsync(url, content);
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"响应内容： {result}");
            }
            else
            {
                Console.WriteLine($"请求失败，状态码： {response.StatusCode}");
            }
        }
        /// <summary>
        /// http创建
        /// </summary>
        private HttpClient HttpCreate()
        {
            var client = HttpClientFactory.Create();
            if (IsUseToken)
            {
                client.DefaultRequestHeaders.Authorization = CreateBasicHeader();
            }
            return client;
        }
        /// <summary>
        /// 创建token请求头
        /// </summary>
        /// <returns></returns>
        public static AuthenticationHeaderValue CreateBasicHeader()
        {
            return new AuthenticationHeaderValue("Bearer", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySWQiOjEzMDAwMDAwMDAxMTEsIlRlbmFudElkIjoxMzAwMDAwMDAwMDAxLCJBY2NvdW50IjoiYWRtaW4iLCJSZWFsTmFtZSI6Iuezu-e7n-euoeeQhuWRmCIsIkFjY291bnRUeXBlIjo0LCJPcmdJZCI6MTMwMDAwMDAwMDEwMSwiT3JnTmFtZSI6IuWNleS9jeWQjeensFhYWCIsIk9yZ1R5cGUiOiIxMDEiLCJpYXQiOjE3MDI4OTA0MDUsIm5iZiI6MTcwMjg5MDQwNSwiZXhwIjoxNzAzNDk1MjA1LCJpc3MiOiJUbG9uZyIsImF1ZCI6IlRsb25nIn0.IuSACmgDd_oI6-hqGIaoOSIZKNLh-F0IIIH2lYf4GmU");
        }
    }
}
